import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/plan.dart';

class PlanRepository {
  static final PlanRepository _instance = PlanRepository._internal();
  factory PlanRepository() => _instance;
  PlanRepository._internal();

  // 创建计划
  Future<int> createPlan(Plan plan) async {
    final db = await DBHelper.database;
    return await db.insert('plan', plan.toMap());
  }

  // 获取所有计划
  Future<List<Plan>> getAllPlans() async {
    final db = await DBHelper.database;
    final res = await db.query('plan', orderBy: 'startTime ASC');
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 根据用户ID获取计划
  Future<List<Plan>> getPlansByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'startTime ASC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 根据ID获取计划
  Future<Plan?> getPlanById(int id) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'id = ?',
      whereArgs: [id],
      limit: 1,
    );
    if (res.isNotEmpty) {
      return Plan.fromMap(res.first);
    }
    return null;
  }

  // 更新计划
  Future<int> updatePlan(Plan plan) async {
    final db = await DBHelper.database;
    return await db.update(
      'plan',
      plan.toMap(),
      where: 'id = ?',
      whereArgs: [plan.id],
    );
  }

  // 删除计划
  Future<int> deletePlan(int id) async {
    final db = await DBHelper.database;
    return await db.delete('plan', where: 'id = ?', whereArgs: [id]);
  }

  // 获取今天未完成的计划（排除已超时的计划）
  Future<List<Plan>> getTodayUncompletedPlans(int userId) async {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final todayEnd = today.add(Duration(days: 1)).subtract(Duration(milliseconds: 1));

    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: '''
        userId = ? AND
        state = 'uncompleted' AND
        endTime > ? AND
        ((startTime <= ? AND endTime >= ?) OR
         (startTime >= ? AND startTime <= ?))
      ''',
      whereArgs: [
        userId,
        now.millisecondsSinceEpoch, // 只显示结束时间晚于当前时间的计划
        todayEnd.millisecondsSinceEpoch,
        today.millisecondsSinceEpoch,
        today.millisecondsSinceEpoch,
        todayEnd.millisecondsSinceEpoch,
      ],
      orderBy: 'endTime ASC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 获取本周的计划
  Future<List<Plan>> getThisWeekPlans(int userId) async {
    final now = DateTime.now();
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));
    final endOfWeek = startOfWeek.add(Duration(days: 6));
    
    final weekStart = DateTime(startOfWeek.year, startOfWeek.month, startOfWeek.day);
    final weekEnd = DateTime(endOfWeek.year, endOfWeek.month, endOfWeek.day, 23, 59, 59);

    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: '''
        userId = ? AND 
        ((startTime <= ? AND endTime >= ?) OR 
         (startTime >= ? AND startTime <= ?))
      ''',
      whereArgs: [
        userId,
        weekEnd.millisecondsSinceEpoch,
        weekStart.millisecondsSinceEpoch,
        weekStart.millisecondsSinceEpoch,
        weekEnd.millisecondsSinceEpoch,
      ],
      orderBy: 'startTime ASC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 更新计划状态
  Future<int> updatePlanState(int planId, String state) async {
    final db = await DBHelper.database;
    return await db.update(
      'plan',
      {'state': state},
      where: 'id = ?',
      whereArgs: [planId],
    );
  }

  // 批量更新超时的计划状态为失败
  Future<void> updateExpiredPlansToFailed(int userId) async {
    final now = DateTime.now();
    final db = await DBHelper.database;
    await db.update(
      'plan',
      {'state': 'failed'},
      where: 'userId = ? AND state = ? AND endTime < ?',
      whereArgs: [userId, 'uncompleted', now.millisecondsSinceEpoch],
    );
  }

  // 获取未完成的计划
  Future<List<Plan>> getNotStartedPlans(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'userId = ? AND state = ?',
      whereArgs: [userId, 'uncompleted'],
      orderBy: 'startTime ASC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 获取已完成的计划
  Future<List<Plan>> getCompletedPlans(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'userId = ? AND state = ?',
      whereArgs: [userId, 'completed'],
      orderBy: 'endTime DESC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 获取进行中的计划
  Future<List<Plan>> getInProgressPlans(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'userId = ? AND state = ?',
      whereArgs: [userId, 'in_progress'],
      orderBy: 'startTime ASC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }

  // 获取过去30天的历史计划
  Future<List<Plan>> getLast30DaysPlans(int userId) async {
    final now = DateTime.now();
    final thirtyDaysAgo = now.subtract(Duration(days: 30));
    final futureLimit = now.add(Duration(days: 7)); // 包含未来7天的计划

    final db = await DBHelper.database;
    final res = await db.query(
      'plan',
      where: 'userId = ? AND startTime >= ? AND startTime <= ?',
      whereArgs: [
        userId,
        thirtyDaysAgo.millisecondsSinceEpoch,
        futureLimit.millisecondsSinceEpoch,
      ],
      orderBy: 'startTime DESC',
    );
    return res.map((map) => Plan.fromMap(map)).toList();
  }
}
